package com.arina.onepagesmarthome;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.ToggleButton;



public class phongngulau1_activity extends Activity {

	Handler handler;
	NetworkChangeReceiver networkstatus=new NetworkChangeReceiver();
	final int delay = 1000;//thoi gian cho truoc khi thuc hien lenh dau tien
	final int period = 2000;//thoi gian lap lai
	private  String[] MySSID ;
	
	Relay[] arrRelay;
	Runnable r;
	MasterBoard master;
	
	//khai bao cac bo relay cho activity
	Relay relay120;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phongngulau1);

		MySSID=((globaldata) this.getApplication()).ssid;
		master=((globaldata) this.getApplication()).masterboard.get(0);
		
		relay120=new Relay(master, 20, 120, 12);
		arrRelay=new Relay[]{relay120};
		
		//gan button cho relay 110
		arrRelay[0].ArrButton[0]=(ToggleButton)findViewById(R.id.channel1);
		arrRelay[0].ArrButton[1]=(ToggleButton)findViewById(R.id.channel2);
		arrRelay[0].ArrButton[2]=(ToggleButton)findViewById(R.id.channel3);
		arrRelay[0].ArrButton[3]=(ToggleButton)findViewById(R.id.channel8);
		arrRelay[0].ArrButton[4]=(ToggleButton)findViewById(R.id.channel6);
		arrRelay[0].ArrButton[5]=(ToggleButton)findViewById(R.id.channel4);
		arrRelay[0].ArrButton[6]=(ToggleButton)findViewById(R.id.channel5);
		arrRelay[0].ArrButton[8]=(ToggleButton)findViewById(R.id.channel7);
		arrRelay[0].setOnClickListener( COMMAND_TYPE.REVERSE, 0);
		

		registerReceiver(networkstatus, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
		handler=new Handler();

		r = new Runnable() {
			public void run() {
				//Toast.makeText(getApplicationContext(),"update status",Toast.LENGTH_SHORT).show();
				updateStatus(handler);
				handler.postDelayed(this, period);
			}
		};

		handler.postDelayed(r, delay);
		if (savedInstanceState != null) {
			return;
		}
	}

	private void updateStatus(final Handler mHandler) {
		Thread th=new Thread(){
			public void run(){
				for(int i=0;i<arrRelay.length;i++)
				{
					arrRelay[i].readStatusHTTP();
				}

				mHandler.post(new Runnable() {

					@Override
					public void run() {
						for(int positionRelay=0;positionRelay<arrRelay.length;positionRelay++)
						{
							if(arrRelay[positionRelay].Status!=null)
								updateUI(arrRelay[positionRelay].Status,positionRelay);

						}

					}
				});
			};
		};
		th.start();
	}
	private void updateUI(boolean[] arrStatus,int positionRelay) {

		for(int i=0;i<arrRelay[positionRelay].ArrButton.length;i++)
		{
			if(arrRelay[positionRelay].ArrButton[i]!=null)
				arrRelay[positionRelay].ArrButton[i].setChecked(!arrStatus[i]);
		}


	}




	private class NetworkChangeReceiver extends BroadcastReceiver{
		private NETWORK_STATUS currNetworkStatus;

		//private static final String MyMAC = "48:f8:b3:32:71:80";
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			getNetworkState(context);
		}

		public void getNetworkState(Context context) {

			if(Connectivity.isConnected(context))
			{
				if(Connectivity.isConnectedMobile(context))//mobile
				{
					currNetworkStatus=NETWORK_STATUS.MOBILE;
				}
				else if(Connectivity.isConnectedWifi(context))//wifi
				{
					WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
					WifiInfo wifiInfo = wifiManager.getConnectionInfo();
					String currSSID=wifiInfo.getSSID().trim();
					if (currSSID.startsWith("\"") && currSSID.endsWith("\"")){
						currSSID = currSSID.substring(1, currSSID.length()-1);
					}
					for(int i=0;i<MySSID.length;i++)
					{
						if(!currSSID.equalsIgnoreCase(MySSID[i]))
						{
							//ket noi wifi noi bo
							currNetworkStatus=NETWORK_STATUS.EXTERNAL;
							break;
						}
						currNetworkStatus=NETWORK_STATUS.LOCAL;
					}
				}
			}
			else
			{
				currNetworkStatus=NETWORK_STATUS.NOT_CONNECTED;
			}
			master.setCurrentAddress(currNetworkStatus);
			Toast.makeText(getApplicationContext(), currNetworkStatus.toString(), Toast.LENGTH_SHORT).show();
		}

	}


	public char[] getMacId() {

		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		return wifiInfo.getBSSID().toCharArray();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.one_page_smarthome, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		handler.removeCallbacks(r);
		unregisterReceiver(networkstatus);
	}

	@Override
	protected void onResume() {
		super.onResume();
		handler.post(r);
		registerReceiver(networkstatus, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

	}


}
